import { UserInfoAPI, loginAPI } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'

const state = {
  // 定义token 从本地拿
  token: getToken(),
  // 用户信息
  userinfo: {},
  // 定义一个路由数组
  routers: []
}

const mutations = {
  svaRouters(state, payload) {
    state.routers = payload
  },
  // 修改将来传过来的token值
  loginAction(state, payload) {
    state.token = payload
  },
  loginUserInfo(state, payload) {
    state.userinfo = payload
  }
}

const actions = {
  // 发登录请求 // 完善登录请求逻辑
  async loginActionApi({ commit }, payload) {
    const res = await loginAPI(payload)
    // console.log(res)
    setToken(res.data)// 存token在本地
    // Message.success('登录成功')
    // 调用mutations 里面的方法，传值，然后mutations 就可以修改state里面的值
    commit('loginAction', res.data)
    router.push('/')
  },
  // 发送用户信息请求
  async userActionApi({ commit }) {
    const res = await UserInfoAPI()
    // console.log(res)
    commit('loginUserInfo', res.data)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

